// pages/orders/orders_confirm.js
const app = getApp();
import {
  OrdersModel
} from "../../utils/models/orders/Orders-models";
import {
  UserModels
} from "../../utils/models/user/User-models";
var userModel = new UserModels;
var ordersModel = new OrdersModel;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mobile: '',
    remarks: '',
    address:'广东省佛山市南海区',
    goodsInfo: {
      title : '大海私房菜 | 低至￥58！海鲜牛肉应有尽有',
      label : '晚市海鲜牛肉火锅放题',
      cover : '/images/test/list.png',
      price : '29.90',
      original_price : '68.00',
      num : 1
    },
    pay : '0.00',
    idx:0,

    address : '',
    linkname : '',
    mobile : '',
    invite_id : 0,
  },

  // 数量增加
  jia: function() {
    var num = parseInt(this.data.goodsInfo.num) + 1 ;
    var goodsInfo = this.data.goodsInfo;
    goodsInfo['num'] = num;
    this.setData({
      goodsInfo : goodsInfo,
      pay : parseFloat(parseFloat(this.data.goodsInfo.price) * num).toFixed(2)
    })
  },

  // 数量减少
  jian: function(){
    if(this.data.goodsInfo.num > 1) {
      var num = parseInt(this.data.goodsInfo.num) - 1 ;
      var goodsInfo = this.data.goodsInfo;
      goodsInfo['num'] = num;

      this.setData({
        goodsInfo : goodsInfo,
        pay : parseFloat(parseFloat(this.data.goodsInfo.price) * num).toFixed(2)
      })
    }
    
  },

  // 手机号码
  mobileInput: function(e) {
    this.setData({
      mobile: e.detail.value
    })
  },
  getPhoneNumber:function(e){
    console.log(e);
  },

  // 留言
  remarksInput: function(e) {
    this.setData({
      remarks: e.detail.value
    })
  },

  // 选择地址
  chooseAddress() {
    var that = this;

    wx.getSetting({
        success(res) {
            // 判断定位的授权
            if (!res.authSetting['scope.userLocation']) {
                console.log('需要授权')
                wx.authorize({
                    scope: 'scope.userLocation',
                    success() {
                        that.chooseAddressInfo();
                    },
                    fail(errMsg) {
                       
                        wx.showModal({
                            title: '用户未授权',
                            content: '请开启相关权限,以便更好使用小程序哦！',
                            showCancel: true,
                            success: function (res) {
                                if (res.confirm) {
                                    wx.openSetting({
                                        success: function (res) {
                                            console.log(res.authSetting)
                                            if (res.authSetting) {
                                                that.chooseAddressInfo();
                                            } else {
                                                wx.showToast({
                                                    icon: 'none',
                                                    title: '获取地址失败'
                                                })
                                            }
                                        },
                                        fail: function (res) {
                                            wx.showToast({
                                                icon: 'none',
                                                title: '获取地址失败'
                                            })
                                        },
                                    })
                                } else if (res.cancel) {
                                    wx.showToast({
                                        icon: 'none',
                                        title: '用户已取消授权',
                                    })
                                }
                            },
                            fail: function (res) {
                                wx.showToast({
                                    icon: 'none',
                                    title: '获取地址失败'
                                })
                            },
                        })
                    }
                })
            } else {
                console.log('已授权')

                that.chooseAddressInfo();
            }
        }
    })


   
  },

  chooseAddressInfo : function() {
    var that = this;
    wx.chooseAddress({
      success: (res) => {
        if(res) {
          var address = res.provinceName + res.cityName + res.countyName + res.detailInfo;
          var linkname = res.userName;
          var mobile = res.telNumber;
          userModel.setUpAddress(res,function(res){
            if(res.code > 0){
              wx.showToast({
                icon: 'none',
                title: '修改成功'
              })
            }
          })
          that.setData({
            address,
            linkname,
            mobile
          })
          
        }

        wx.showToast({
          icon: 'none',
          title: '修改成功'
        })
       
      },
      fail: function(err) {
        console.log(err)
       
      }
    })
  },

  // 立即支付
  goPay: function() {
    var num = parseInt(this.data.goodsInfo.num);
    var price = parseFloat(this.data.goodsInfo.price);
    var mobile =  this.data.mobile;
    
    if(num <= 0) {
      wx.showToast({
        icon: 'none',
        title: '购买数量至少1份'
      })
      return;
    }else if(num*price <0) {
      wx.showToast({
        icon: 'none',
        title: '错误操作'
      })
      return;
    }else if( !(/^1[34578]\d{9}$/.test(mobile)) || mobile.length>11 ) {
      wx.showToast({
        icon: 'none',
        title: '请输入正确的手机号码'
      })
      return;
    }
    var goodsInfo = this.data.goodsInfo;
    if(goodsInfo.type == 1){
        if (!this.data.address){
            wx.showToast({
                icon: 'none',
                title: '请输入收货地址'
            })
            return;
        }
    }
    goodsInfo.pay = this.data.pay;
    goodsInfo.mobile = this.data.mobile;
    goodsInfo.remarks = this.data.remarks;
    goodsInfo.idx = this.data.idx;
    goodsInfo.invite_id = this.data.invite_id;
    ordersModel.submitOrder(goodsInfo,function(res){
      var jsApiParameters = res.data.jsApiParameters;
      var oid = res.data.oid;
      wx.requestPayment(
        {
          'timeStamp': jsApiParameters.timeStamp,
          'nonceStr': jsApiParameters.nonceStr,
          'package': jsApiParameters.package,
          'signType': jsApiParameters.signType,
          'paySign': jsApiParameters.paySign,
          'success': function (res) { 
            // console.log(res)
            wx.navigateTo({
              url: './orders_detail?id='+oid,
            })
          },
          'fail': function (res) { 
            wx.showToast({
              title: '支付取消',
              icon:'error'
            })
          },
          'complete': function (res) { }
        })
    })
    // 微信支付操作
    // this.wxPay(1);
  },


  /*
 调起微信支付 
 @param 支付价格，不填写默认为1分钱
*/
wxPay: function (total_fee) {
  var total_fee = total_fee; 
  wx.login({
    success: res => {
       //code 用于获取openID的条件之一
      var code = res.code;
      wx.request({
        url: 'http://192.168.2.224/pay.php',
        method: "POST",
        data: {
          total_fee: 0.01,
          code: code,
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {  //后端返回的数据
          var data = res.data;
          console.log(data);
        
          wx.requestPayment({
            timeStamp: data['timeStamp'],
            nonceStr: data['nonceStr'],
            package: data['package'],
            signType: data['signType'],
            paySign: data['paySign'],
            success: function (res) {
              wx.showModal({
                title: '支付成功',
                content: '',
              })
            },
            fail: function (res) {
              console.log(res);
            }
          })
        },
        fail:function(res2) {
          console.log(res2)
        }
      });
 
 
    }
  })
  
},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    var param = {
      'id': options.id,
      'idx': options.idx
    }
    this.getDetail(param);
    var userinfo = wx.getStorageSync('userinfo');
    this.setData({
      mobile:userinfo.mobile,
      idx:options.idx,
      invite_id:invite_id
    });
  },
  getDetail:function(param){
    let that = this;
    ordersModel.orderComfirm(param,function(res){
      var goodsInfo = res.data;
      goodsInfo.num = 1;
      var address = goodsInfo.shouhuo.address;
      var linkman = goodsInfo.shouhuo.shouhuo_name;
      var mobile =  goodsInfo.shouhuo.shouhuo_phone;
      that.setData({
        goodsInfo: goodsInfo,
        pay: parseFloat(goodsInfo.price) * parseInt(goodsInfo.num),
        address:address,
        linkname:linkman,
        mobile:mobile,
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(!wx.getStorageSync('userinfo').mobile){
      wx.showModal({
        title: '提示',
        content:'请前往个人中心绑定手机号',
        success: function (res) {
          if (res.confirm) {  
            wx.switchTab({
              url: '../my/my',
            })
          } else {   
            wx.navigateBack({
              delta: -1,
            })
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})